package com.zhao.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhao.Util.FileSize;
import com.zhao.Util.FileTools;
import com.zhao.Util.HttpContextUtil;
import com.zhao.Util.WalletUtil;
import com.zhao.comm.log.MyLog;
import com.zhao.pojo.*;
import com.zhao.pojo.result.Response;
import com.zhao.pojo.result.ResponseResult;
import com.zhao.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    ArticleService articleService;
    @Autowired
    GroupsService groupsService;
    @Autowired
    StatisticService statisticService;
    @Autowired
    RoleService roleService;
    @Autowired
    WalletService walletService;
    //写文章页
    @RequestMapping("/add_article")
    public String writeArticle(Model model){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<Groups> wrapper = new QueryWrapper<Groups>();
        wrapper.eq("uid",loginUser.getUserId());
        Collection<Groups> groups = groupsService.list(wrapper);
        model.addAttribute("groups",groups);
        return "admin/add_article";
    }
    //设置是否top
    @RequestMapping("/toparticle/{id}/{top}")
    @ResponseBody
    public String topArticle(@PathVariable String id,@PathVariable String top){
        System.out.println(id+" ++++++ "+top);
        Article article = articleService.getOne(new QueryWrapper<Article>().eq("article_id", id));
        Statistic statistic = statisticService.getOne(new QueryWrapper<Statistic>().eq("id", article.getBrowse()));
        System.out.println(top);
        if (Integer.parseInt(top) != 0) {
            statistic.setTop("0");
        } else {
            statistic.setTop("1");
        }
        System.out.println(statistic.getTop());
        statisticService.updateById(statistic);
        //return "redirect:/article/data_article";
        return "1";
    }
    //发布文章或修改文章
    //@MyLog(value = "发布/修改文章")  //日志
    @PostMapping("/addArticle")
    @ResponseBody
    public ResponseResult addArticle(Article article) {
       // User loginUser = (User)request.getSession().getAttribute("loginUser");
        System.out.println("=================================================="+article);
        if (article.getArticleId()!=null){
            Article byId = articleService.getById(article.getArticleId());
            Groups old = groupsService.getById(byId.getGroupsId());
            Groups news = groupsService.getById(article.getGroupsId());
            old.setGnum(old.getGnum()-1);
            news.setGnum(news.getGnum()+1);
            groupsService.updateById(old);
            groupsService.updateById(news);
            articleService.updateById(article);
        }else {
            System.out.println("=================================================="+article);
            User loginUser = (User) SecurityUtils.getSubject().getPrincipal();

            article.setAuthor(loginUser.getUserAccount());
            articleService.save(article);
            //分类表加+1
            QueryWrapper<Groups> wrapper = new QueryWrapper<>();
            wrapper.eq("groups_id", article.getGroupsId());
            Groups one = groupsService.getOne(wrapper);
            one.setGnum(one.getGnum() + 1);
            //给新文章设置 创建统计表 数据+1
            Statistic statistic = new Statistic();
            QueryWrapper<Article> inSql = new QueryWrapper<Article>().inSql("article_id", "select max(article_id) from article");
            Article newOne = articleService.getOne(inSql);
            statistic.setArticleId(newOne.getArticleId());
            //增加积分
            Wallet wallet = walletService.getOne(new QueryWrapper<Wallet>().eq("uid", one.getUid()));

            walletService.updateById(WalletUtil.ComputeIntegral(wallet,10));
            statisticService.save(statistic);
            groupsService.updateById(one);
            newOne.setBrowse(statisticService.getOne(new QueryWrapper<Statistic>().inSql("id", "select max(id) from statistic")).getId() + "");
            articleService.updateById(newOne);
        }
        return Response.makeOKRsp("已发布");
    }
    //文章查询一条显示
    @RequestMapping("/edit_article")
    public String editArticle(Integer id,Model model){
        System.out.println("============================================================"+id);
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<Groups> wrapper = new QueryWrapper<Groups>();
        wrapper.eq("uid",loginUser.getUserId());
        Collection<Groups> groups = groupsService.list(wrapper);
        Article article = articleService.getById(id);
        model.addAttribute("b",article);
        model.addAttribute("groups",groups);
        return "admin/update_article";
    }
    //删除文章
    //@MyLog(value = "删除文章")  //日志
    @GetMapping("/delArticle/{id}")
    public String delArticle(@PathVariable("id")Integer id){
        System.out.println(id);
        Article article = articleService.getById(id);
        //文章表删除文章
        articleService.removeById(id);
        //分类表数据-1
        QueryWrapper<Groups> wrapper=new QueryWrapper<>();
        wrapper.eq("groups_id",article.getGroupsId());
        Groups one = groupsService.getOne(wrapper);
        one.setGnum(one.getGnum()-1);
        groupsService.updateById(one);
        //统计表删除数据
        statisticService.remove(new QueryWrapper<Statistic>().eq("article_id",article.getArticleId()));
        return "redirect:/article/data_article";
    }

    //管理文章
    @RequestMapping("/data_article")
    public String articleQuery(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                               @RequestParam(value = "size",required = false,defaultValue = "5")Integer size,
                               @RequestParam(value = "title",required = false)String title,
                               Model model) {
        //判断当前用户身份 用户查自己 管理员和 超级管理员 查全部
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        String roleName=roleService.getUserRoleName(loginUser.getUserId());
        String author=null;
        if (roleName.equals("用户")){
            author=loginUser.getUserAccount();
        }
        Page<Article> page = articleService.selectListPageTop(pageNum, size, title,author);
        model.addAttribute("articles",page);
        return "admin/data_article";
    }

    //博客图片上传问题
    @RequestMapping("/file/upload")
    @ResponseBody
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file) throws IOException {
        //上传路径保存设置

        //获得SpringBoot当前项目的路径：System.getProperty("user.dir")
        String path = System.getProperty("user.dir")+"/upload/file/";
        System.out.println(path);
        //按照月份进行分类：
        Calendar instance = Calendar.getInstance();
        String month = (instance.get(Calendar.MONTH) + 1)+"月";
        path = path+month;

        File realPath = new File(path);
        //log.info("文件创建：{}",file.getOriginalFilename());
        if (!realPath.exists()){
            realPath.mkdir();
            //log.info("数据库备份结束，备份结果：{}",);
        }

        //上传文件地址
        System.out.println("上传文件保存地址："+realPath);
        //获取文件后缀
        String hou = file.getOriginalFilename();
         hou = hou.substring(hou.indexOf("."),hou.length());
        //解决文件名字问题：我们使用uuid;
        String filename = "ks-"+ UUID.randomUUID().toString().replaceAll("-", "")+hou;
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(realPath +"/"+ filename));

        //给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url","/upload/file/"+month+"/"+ filename);
        res.put("success", 1);
        res.put("message", "upload success!");
        return res;
    }

    //用导入文件 TXT 和 md文件
    @RequestMapping("/fileupload")
    @ResponseBody
    public ResponseResult<Map<String,String>> upload(Datafile datafile, MultipartFile file) throws IOException {
        System.out.println("===================================>"+datafile);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());

        // uploads文件夹位置
        //String rootPath = request.getSession().getServletContext().getRealPath("resource/uploads/");
        //String rootPath =System.getProperty("user.dir")+"/src/main/resources/uploads/ziyuan/";
        String rootPath =System.getProperty("user.dir")+"/upload/temp/";
        // 原始名称
        String originalFileName = file.getOriginalFilename();
        // 新文件名
        String newFileName = "sliver" + res + originalFileName.substring(originalFileName.lastIndexOf("."));
        // 新文件
        File newFile = new File(rootPath + File.separator + newFileName);
        // 判断目标文件所在目录是否存在
        if( !newFile.getParentFile().exists()) {
            // 如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }
        file.transferTo(newFile);
        // 文件绝对路径

        String path = newFile.getPath();
        String fileContent = FileTools.ReadFileContent(path);
        Map<String,String> map = new HashMap<>();
        map.put("content",fileContent);
        String prefix = getPrefix(originalFileName,false);
        map.put("title", prefix);
        //删除临时文件
        System.out.println("删除临时文件");
        boolean b = FileTools.deleteFile(path);
        System.out.println("删除临时文件："+b);
        return  Response.makeOKRspData(map);
    }
    public String getPrefix(String fileName, boolean toLower) {
        if (fileName.contains(".")) {
            String prefix = fileName.substring(0,fileName.lastIndexOf("."));
            if (toLower) {
                return trimilSpace(prefix.toLowerCase());
            }
            return trimilSpace(prefix);
        }
        return null;
    }
    public String trimilSpace(String input) {
        if (input == null) {
            return null;
        }
        String result = input.replaceAll("\u00A0", "").replaceAll("\u200B", "").replaceAll("\u2002", "")
                .replaceAll("\u200C", "").replaceAll("\u200D", "").replaceAll("\uFEFF", "").trim();
        if ("".equals(input)) {
            return null;
        }
        return result;
    }
}
